import { FastifyInstance } from "fastify";
import { Op } from "sequelize";
import { Student } from "@db";
import { getFullName } from "@helpers";
import { Type, Static } from "@sinclair/typebox";
import { config } from "@config";

const ratingParams = Type.Object({
    page: Type.Optional(Type.Number({ default: 0 })),
    professionalRole: Type.Optional(Type.String()),
});

export const rating = async (fastify: FastifyInstance) => {
    fastify.get<{ Querystring: Static<typeof ratingParams> }>(
        "/student/rating",
        {
            preHandler: async (req, res) => {
                if ("student" in req.session)
                    return await fastify.auth("student")(req, res);
            },
            schema: {
                tags: ["student"],
                querystring: ratingParams,
            },
        },
        async (req, res) => {
            console.log(req.student);
            const { page, professionalRole } = req.query;
            let index = 0;

            const where: any = {};
            if (professionalRole) where.professionalRole = professionalRole;

            const { count, rows } = await Student.findAndCountAll({
                where,
                order: [["score", "DESC"]],
                offset: page * 50,
                limit: 50,
            });
            const rating = rows.map(
                ({ id, firstName, lastName, patronymic, score, photo }, i) => {
                    //TODO: подумать ещё
                    if (!rows[i - 1] || rows[i - 1].score !== score) index++;
                    return {
                        index,
                        id,
                        name: getFullName(lastName, firstName, patronymic),
                        photo: photo
                            ? "https://" +
                              config.host +
                              "/files/avatars/" +
                              photo
                            : null,
                        score,
                    };
                }
            );

            if (req.student) {
                const currentStudentInRating = await Student.count({
                    where: {
                        score: {
                            [Op.gt]: req.student.score,
                        },
                    },
                });

                return res.send({
                    pages: Math.ceil(count / 50),
                    students: rating,
                    currentPlace: currentStudentInRating + 1,
                });
            } else {
                return res.send({
                    pages: Math.ceil(count / 50),
                    students: rating,
                });
            }
        }
    );
};
